<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!--  文字提示区域 -->
      <el-alert title="消息提示的文案" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域  -->
      <el-steps :space="200" :active="activeIndex - 0 " finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs栏 -->
      <el-form :model="addGoodsForm" :rules="addGoodsFormRules" ref="addGoodsFormRefs" label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabsLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="goodCateLists"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyGoodCates" :key="item.attr_id">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="cb" v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyGoodCates" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :action="actionUrl" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :headers="headersObj" :on-success="handelSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addGoodsForm.goods_introduce">

            </quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" @click="handelAdd">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片对话框 -->
    <el-dialog title="预览图片" :visible.sync="previewImageDialog" width="50%">
      <img :src="previewPath" class="preImage" alt="">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data () {
    return {
      activeIndex: '0',
      // 添加商品表单的数据对象
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        // 内容详情
        goods_introduce: '',
        attrs: []
      },
      //  规则
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', tirgger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', tirgger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', tirgger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', tirgger: 'blur' }
        ]
        // goods_cat: [
        //   { required: 'false', message: '请选择商品类型', tirgger: 'blur' }
        // ]
      },
      // 所有商品分类数据对象
      goodCateLists: [],
      // 级联选择器的配置项
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 动态参数数据数组
      manyGoodCates: [],
      // 静态属性数组
      onlyGoodCates: [],
      // 上传图片的路径
      actionUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      //  配置token
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片路径
      previewPath: '',
      // 控制图片显示与隐藏的对话框
      previewImageDialog: false
    }
  },
  methods: {
    // 获取所有商品分类数据
    async getGoodsCateLists () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      this.goodCateLists = res.data
    },
    // 当级联选择器发生改变的时候触发这个函数
    handleChange () {
      console.log(this.addGoodsForm.goods_cat)
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = ['']
      }
    },
    // 当切换标签页时触发这个事件
    beforeTabsLeave (activeName, oldName) {
      if (oldName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 当页签被点击时触发
    async tabClicked () {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.CateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数失败')
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyGoodCates = res.data
        console.log(this.manyGoodCates)
      } else if (this.activeIndex === '2') {
        const {
          data: res
        } = await this.$http.get(`categories/${this.CateId}/attributes`, {
          params: { sel: 'only' }
        })
        console.log(res.data + '1111')
        if (res.meta.status !== 200) {
          return this.$message.error('获取静态属性失败')
        }

        this.onlyGoodCates = res.data
        console.log(this.onlyGoodCates)
      }
    },
    // 预览图片触发的事件处理函数
    handlePreview (file) {
      console.log(file)
      this.previewPath = file.response.data.url
      console.log(this.previewPath)
      this.previewImageDialog = true
    },
    // 移出图片的处理函数
    handleRemove (file) {
      // 1.获取此图片的文件路径
      const filePath = file.response.data.tmp_path
      // 2.从pics图片数组中找到这张图片的索引
      const i = this.addGoodsForm.pics.findIndex(x =>
        x.pic === filePath
      )
      // 3.根据索引删除图片 splice() 方法
      this.addGoodsForm.pics.splice(i, 1)
      console.log(this.addGoodsForm)
    },
    // 监听图片上传成功
    handelSuccess (response) {
      console.log(response)
      // 1.拼接得到一个图片对象
      const picsInfo = {
        pic: response.data.tmp_path
      }

      // 2.push到pics数组中
      this.addGoodsForm.pics.push(picsInfo)
      console.log(this.addGoodsForm)
    },
    // 添加商品的按钮，提交数据
    handelAdd () {
      this.$refs.addGoodsFormRefs.validate(async valid => {
        if (!valid) {
          return this.$message.error('您还没填写相关的信息')
        }
        const form = _.cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.manyGoodCates.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyGoodCates.forEach(item => {
          const info = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodsForm.attrs.push(info)
        })
        form.attrs = this.addGoodsForm.attrs
        // 发起数据请求
        // 商品的名称必须是唯一的
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  created () {
    this.getGoodsCateLists()
  },
  computed: {
    CateId () {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.preImage{
  width: 100%;
}
.el-button{
  margin: 15px 0;
}
</style>
